package com.kun.companion.core.thread;

import com.kun.companion.core.exception.BizException;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 带优先级的FutureTask实现
 * <p>
 * 包装PrioritizedTask以实现任务队列的优先级排序功能，配合PriorityBlockingQueue使用。
 * 通过实现Comparable接口，确保高优先级任务优先执行。
 * </p>
 *
 * @author gzc
 * @since 2025/2/3
 **/
public class PriorityFutureTask<T> extends FutureTask<T>
        implements Comparable<PriorityFutureTask<T>> {

    /**
     * 封装的优先级任务对象
     */
    private final PrioritizedTask prioritizedTask;

    /**
     * 构造函数
     *
     * @param runnable 必须为PrioritizedTask类型
     * @param result   任务执行结果（可为null）
     * @throws IllegalArgumentException 当runnable参数类型不匹配时抛出
     */
    public PriorityFutureTask(Runnable runnable, T result) {
        super(runnable, result);
        if (!(runnable instanceof PrioritizedTask)) {
            throw new BizException("Runnable必须为PrioritizedTask类型，实际类型: " + runnable.getClass().getName()
            );
        }
        this.prioritizedTask = (PrioritizedTask) runnable;
    }

    /**
     * 任务比较方法（数值越大优先级越高）
     */
    @Override
    public int compareTo(PriorityFutureTask<T> other) {
        // 倒序排列实现高优先级优先
        return this.prioritizedTask.compareTo(other.prioritizedTask);

    }

    /**
     * 获取封装的优先级任务
     */
    public PrioritizedTask getPrioritizedTask() {
        return prioritizedTask;
    }
}